﻿using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;

namespace MES.Server.Utility.AuthorizationExt
{
    /// <summary>
    /// 
    /// </summary>
    public class MenuAuthorizeHandler : AuthorizationHandler<MenuAuthorizeRequirement>
    {
        //private IUserManagerService _IUserManagerService;
        public MenuAuthorizeHandler(/*IUserManagerService iUserManagerService*/)
        {
            //_IUserManagerService = iUserManagerService;
        }


        /// <summary>
        /// 解析到token之后，通过token中包含的用户的信息，可以去做业务逻辑的判定
        /// </summary>
        /// <param name="context"></param>
        /// <param name="requirement"></param>
        /// <returns></returns>
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, MenuAuthorizeRequirement requirement)
        {
            if (context.User.Claims == null || context.User.Claims.Count() <= 0)
            {
                context?.Fail();
            }
            else if (context.User.IsInRole("admin"))
            {
                context?.Succeed(requirement);//只要执行这句话就表示验证通过了
            }
            else
            {

                HttpContext httpcontext = (HttpContext)context.Resource!;
                //通过token中包含的按钮权限来校验---解析了token后包含的按钮的权限信息
                {
                    //1. 不用频繁的去查询数据库
                    //2. 无法实时判断权限


                    //List<string> currentUserBtnList = httpcontext.User.Claims
                    //    .Where(c => c.Type.Equals("Btns"))
                    //    .Select(c => c.Value)
                    //    .ToList();

                    ////获取控制器的名称不带后缀
                    //object? controllerName = httpcontext.GetRouteValue("controller");

                    ////获取api的名称，如果是async结尾的，不要async
                    //object? actionName = httpcontext.GetRouteValue("action");

                    //bool iContains = currentUserBtnList
                    //    .Any(m => m.Equals($"{controllerName}-{actionName}", StringComparison.OrdinalIgnoreCase));
                    //if (iContains)
                    //{
                    //    context?.Succeed(requirement);//只要执行这句话就表示验证通过了
                    //}
                    //else
                    //{
                    //    context?.Fail();
                    //}
                }

                //解析到用户信息后, 通过用户的id 去实时查询下用户具备哪些权限
                //链接数据库了
                {
                    //1.实时查询数据库做判断，权限会更加精准
                    //2.性能会差点

                    string? strUserId = httpcontext.User?.Claims?
                         .FirstOrDefault(c => c.Type.Equals(ClaimTypes.Sid))?
                         .Value;

                    if (strUserId == null)
                    {
                        context?.Fail();

                    }
                    else
                    {

                        object? controllerName = httpcontext.GetRouteValue("controller");
                        object? actionName = httpcontext.GetRouteValue("action");
                        context?.Succeed(requirement);
                        //bool bReuslt = await _IUserManagerService.ValidateBtnAsync(Convert.ToInt32(strUserId), $"{controllerName}-{actionName}");

                        //if (bReuslt)
                        //{
                        //    context?.Succeed(requirement);//只要执行这句话就表示验证通过了

                        //}
                        //else
                        //{
                        //    context?.Fail();
                        //}
                    }
                }

            }
            await Task.CompletedTask;
        }
    }
}
